package com.ansion.commonchat.startup.workmanager.bwork.utils;

import androidx.annotation.NonNull;

import com.ansion.commonchat.startup.workmanager.bwork.BWorkInfo;
import com.ansion.commonchat.startup.workmanager.bwork.impl.BWorkManagerImpl;
import com.ansion.commonchat.startup.workmanager.bwork.impl.mode.BWorkSpecDao;
import com.ansion.commonchat.startup.workmanager.bwork.impl.mode.WorkDataCache;
import com.ansion.log.LogTag;
import com.ansion.log.VLog;

/**
 * Created by wanghongjie on 2023/5/11
 * Describe : 用于停止正在运行的工作
 */
public class BStopWorkRunnable implements Runnable {

    private final BWorkManagerImpl mWorkManagerImpl;
    private final String mWorkSpecId;

    public BStopWorkRunnable(
            @NonNull BWorkManagerImpl workManagerImpl,
            @NonNull String workSpecId) {
        mWorkManagerImpl = workManagerImpl;
        mWorkSpecId = workSpecId;
    }

    @Override
    public void run() {
        WorkDataCache workDataCache = mWorkManagerImpl.getWorkDataCache();
        BWorkSpecDao workSpecDao = workDataCache.workSpecDao();
        boolean isStopped;
        if (workSpecDao.getState(mWorkSpecId) == BWorkInfo.State.RUNNING) {
            workSpecDao.setState(BWorkInfo.State.ENQUEUED, mWorkSpecId);
        }
        isStopped = mWorkManagerImpl
                .getProcessor()
                .stopWork(mWorkSpecId);

        if (VLog.OPEN_LOG)
            VLog.d(LogTag.TAG_B_WORK_MANAGER, "BStopWorkRunnable for %s; BProcessor.stopWork = %s",
                    mWorkSpecId,
                    isStopped);

    }
}